package array;

import org.junit.Test;

import java.util.Stack;

public class ValidParentheses20 {
    @Test
    public void test() {
        isValid("()[]{}");
        isValid("([)]");
        isValid("{[]}");
    }

    public boolean isValid(String s) {
        Stack<Character> t = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (isLeft(c)) {
                t.push(c);
            } else if (t.isEmpty()) {
                return false;
            } else {
                if (matches(t.peek(), c)) {
                    t.pop();
                } else {
                    return false;
                }
            }
        }
        System.out.format("s: %s, isValid: %s\n", s, t.isEmpty());
        return t.isEmpty();
    }

    public boolean isLeft(char c) {
        return c == '(' || c == '[' || c == '{';
    }

    public boolean matches(char left, char right) {
        return ((left == '(' && right == ')') || (left == '[' && right == ']') || (left == '{' && right == '}'));
    }
}
